package org.zn.note.jdk.container;

import java.util.*;
import java.util.function.Consumer;

/**
 * {@link LinkedList} 非线程安全
 * 是{@link List}，也是队列{@link Queue}、双端队列{@link Deque}
 * <p>
 * 关于{@link Queue} 队列
 * boolean add(E e); 立即返回，true or IllegalStateException（没空间了）
 * boolean offer(E e); 立即返回，true or false（没空间了）
 * E remove(); 删除并返回，没元素 NoSuchElementException
 * E poll(); 删除并返回，没元素 返null  “poll" 轮训
 * E element(); 返回不删除，没元素 NoSuchElementException
 * E peek(); 返回不删除，没元素 返null  “peek” 窥视、窥见
 * <p>
 * 关于{@link Deque} Deque<E> extends Queue<E> 双端队列
 * 1、和Queue对应的方法，只不过是可以两头操作
 * void addFirst(E e);  void addLast(E e); IllegalStateException
 * boolean offerFirst(E e);  boolean offerLast(E e);
 * E removeFirst(); E removeLast(); NoSuchElementException
 * E pollFirst();  E pollLast();
 * E getFirst(); E getLast(); NoSuchElementException  -- 上面和Queue里是对应，这个是和Queue.element()对应的
 * E peekFirst(); E peekLast();
 * 2、从两头找指定元素并删除
 * boolean removeFirstOccurrence/removeLastOccurrence(Object o);
 * 3、也可作为Stack栈实现 （双端队列本身就可以作为栈用，这里仅仅是包了一层API）
 * void push(E e); = void addFirst(E e);  压栈  “push” 推、压、按
 * E pop(); = E removeFirst();  出栈  “pop" 突然、”砰“、弹出、抛出
 */
public class JdkLinkedList<E> extends AbstractSequentialList<E>
        implements List<E>, Deque<E>, Cloneable, java.io.Serializable {
    transient int size = 0;
    transient JdkLinkedList.Node<E> first; // 指向首节点
    transient JdkLinkedList.Node<E> last; // 指向尾结点

    // 构造函数1：什么也不做
    public JdkLinkedList() {
    }

    // 构造函数2：有初始内容的
    public JdkLinkedList(Collection<? extends E> c) {
        this();
        addAll(c);
    }

    @Override // implements Queue
    public boolean add(E e) {
        linkLast(e);
        return true;
    }

    @Override // implements Queue
    public boolean offer(E e) {
        return add(e);
    }

    @Override // implements Queue
    public E remove() {
        return removeFirst();
    }

    @Override // implements Queue
    public E poll() {
        final Node<E> f = first;
        return (f == null) ? null : unlinkFirst(f);
    }

    @Override // implements Queue
    public E element() {
        return getFirst();
    }

    @Override // implements Queue
    public E peek() {
        final Node<E> f = first;
        return (f == null) ? null : f.item;
    }

    @Override // implements Deque
    public void addFirst(E e) {
        linkFirst(e);
    }

    @Override // implements Deque
    public void addLast(E e) {
        linkLast(e);
    }

    @Override // implements Deque
    public boolean offerFirst(E e) {
        addFirst(e);
        return true;
    }

    @Override // implements Deque
    public boolean offerLast(E e) {
        addLast(e);
        return true;
    }

    @Override // implements Deque
    public E removeFirst() {
        final Node<E> f = first;
        if (f == null) throw new NoSuchElementException();
        return unlinkFirst(f);
    }

    @Override // implements Deque
    public E removeLast() {
        final Node<E> l = last;
        if (l == null) throw new NoSuchElementException();
        return unlinkLast(l);
    }

    @Override // implements Deque
    public E pollFirst() {
        final Node<E> f = first;
        return (f == null) ? null : unlinkFirst(f);
    }

    @Override  // implements Deque
    public E pollLast() {
        final Node<E> l = last;
        return (l == null) ? null : unlinkLast(l);
    }

    @Override  // implements Deque
    public E getFirst() {
        final Node<E> f = first;
        if (f == null) throw new NoSuchElementException();
        return f.item;
    }

    @Override  // implements Deque
    public E getLast() {
        final Node<E> l = last;
        if (l == null) throw new NoSuchElementException();
        return l.item;
    }

    @Override  // implements Deque
    public E peekFirst() {
        final Node<E> f = first;
        return (f == null) ? null : f.item;
    }

    @Override  // implements Deque
    public E peekLast() {
        final Node<E> l = last;
        return (l == null) ? null : l.item;
    }

    @Override  // implements Deque
    public boolean removeFirstOccurrence(Object o) {
        return remove(o);
    }

    @Override  // implements Deque
    public boolean removeLastOccurrence(Object o) {
        if (o == null) {
            for (Node<E> x = last; x != null; x = x.prev) {
                if (x.item == null) {
                    unlink(x);
                    return true;
                }
            }
        } else {
            for (Node<E> x = last; x != null; x = x.prev) {
                if (o.equals(x.item)) {
                    unlink(x);
                    return true;
                }
            }
        }
        return false;
    }

    @Override  // implements Deque
    public void push(E e) {
        addFirst(e);
    }

    @Override  // implements Deque
    public E pop() {
        return removeFirst();
    }

    // Node结构
    private static class Node<E> {
        E item; // 本节点数据
        Node<E> next; // 指向后一节点
        Node<E> prev; // 指向前一节点

        Node(Node<E> prev, E element, Node<E> next) {
            this.item = element;
            this.next = next;
            this.prev = prev;
        }
    }

    // 头部添加node
    private void linkFirst(E e) {
        final Node<E> f = first; // 原有的第一个node
        final Node<E> newNode = new Node<>(null, e, f);
        first = newNode;
        if (f == null) // 原来没有node，last指向当前node （此时也只有当前新建的这1个node）
        last = newNode;
        else
        f.prev = newNode; // 原有的first：prev本来是null，因为前面没有node了；现在指向newNode，因为在头部新增了
        size++;
        modCount++;
    }

    // 尾部添加node
    void linkLast(E e) {
        final Node<E> l = last;
        final Node<E> newNode = new Node<>(l, e, null);
        last = newNode;
        if (l == null)
            first = newNode;
        else
            l.next = newNode;
        size++;
        modCount++;
    }

    // 在指定节点(succ)前面加node(e)  "node-->succ-->node" => "node-->e-->succ-->node"
    void linkBefore(E e, Node<E> succ) {
        final Node<E> pred = succ.prev;
        final Node<E> newNode = new Node<>(pred, e, succ);
        succ.prev = newNode;
        if (pred == null)
            first = newNode;
        else
            pred.next = newNode;
        size++;
        modCount++;
    }

    // 删除节点
    // 单从本方法看：是删除f前面的所有节点，包括f也删了
    // 单是内部调用的时候，都是 final Node<E> f = first;
    // 所以也就是取出并删除头部第一个node
    private E unlinkFirst(Node<E> f) {
        final E element = f.item;
        final Node<E> next = f.next;
        f.item = null;
        f.next = null;
        // 讲first指向f.next，说明f前面的node全删了！
        first = next; // first = f.next，不用判断next是不是null
        if (next == null) // f.next = null，说明f是最后一个节点了，删完f就没有node了，所以last=null
            last = null;
        else // f不是最后一个节点
            next.prev = null;
        size--;
        modCount++;
        return element;
    }

    // 和上面unlinkFirst同理
    private E unlinkLast(Node<E> l) {
        // assert l == last && l != null;
        final E element = l.item;
        final Node<E> prev = l.prev;
        l.item = null;
        l.prev = null; // help GC
        last = prev;
        if (prev == null)
            first = null;
        else
            prev.next = null;
        size--;
        modCount++;
        return element;
    }

    // 这是经典的删除一个节点
    E unlink(Node<E> x) {
        // 先拿到当前node的 item、next、prev
        final E element = x.item;
        final Node<E> next = x.next;
        final Node<E> prev = x.prev;

        if (prev == null) { // 前面没有节点，说明x是第一个
            first = next;
        } else { // x前面有节点，就 x.prev.next = x.next
            prev.next = next;
            x.prev = null;
        }

        if (next == null) { // 后面没有节点，说明x是最后一个
            last = prev;
        } else { // x后面有节点，就 x.next.prev = x.prev
            next.prev = prev;
            x.next = null;
        }

        x.item = null; // 最后全清了，可以在这里一起 x.next=null x.prev=null x.item=null
        size--;
        modCount++;
        return element;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public Iterator<E> descendingIterator() {
        return new DescendingIterator();
    }

    /**
     * Adapter to provide descending iterators via ListItr.previous
     */
    private class DescendingIterator implements Iterator<E> {
        private final ListItr itr = new ListItr(size());
        public boolean hasNext() {
            return itr.hasPrevious();
        }
        public E next() {
            return itr.previous();
        }
        public void remove() {
            itr.remove();
        }
    }

    @Override
    public ListIterator<E> listIterator(int index) {
        checkPositionIndex(index);
        return new ListItr(index);
    }

    private void checkPositionIndex(int index) {
        if (!isPositionIndex(index))
            throw new IndexOutOfBoundsException("...");
    }

    private boolean isPositionIndex(int index) {
        return index >= 0 && index <= size;
    }

    private class ListItr implements ListIterator<E> {
        private Node<E> lastReturned;
        private Node<E> next;
        private int nextIndex;
        private int expectedModCount = modCount;

        ListItr(int index) {
            // assert isPositionIndex(index);
            next = (index == size) ? null : node(index);
            nextIndex = index;
        }

        public boolean hasNext() {
            return nextIndex < size;
        }

        public E next() {
            checkForComodification();
            if (!hasNext())
                throw new NoSuchElementException();

            lastReturned = next;
            next = next.next;
            nextIndex++;
            return lastReturned.item;
        }

        public boolean hasPrevious() {
            return nextIndex > 0;
        }

        public E previous() {
            checkForComodification();
            if (!hasPrevious())
                throw new NoSuchElementException();

            lastReturned = next = (next == null) ? last : next.prev;
            nextIndex--;
            return lastReturned.item;
        }

        public int nextIndex() {
            return nextIndex;
        }

        public int previousIndex() {
            return nextIndex - 1;
        }

        public void remove() {
            checkForComodification();
            if (lastReturned == null)
                throw new IllegalStateException();

            Node<E> lastNext = lastReturned.next;
            unlink(lastReturned);
            if (next == lastReturned)
                next = lastNext;
            else
                nextIndex--;
            lastReturned = null;
            expectedModCount++;
        }

        public void set(E e) {
            if (lastReturned == null)
                throw new IllegalStateException();
            checkForComodification();
            lastReturned.item = e;
        }

        public void add(E e) {
            checkForComodification();
            lastReturned = null;
            if (next == null)
                linkLast(e);
            else
                linkBefore(e, next);
            nextIndex++;
            expectedModCount++;
        }

        public void forEachRemaining(Consumer<? super E> action) {
            Objects.requireNonNull(action);
            while (modCount == expectedModCount && nextIndex < size) {
                action.accept(next.item);
                lastReturned = next;
                next = next.next;
                nextIndex++;
            }
            checkForComodification();
        }

        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

    Node<E> node(int index) {
        // assert isElementIndex(index);

        if (index < (size >> 1)) {
            Node<E> x = first;
            for (int i = 0; i < index; i++)
                x = x.next;
            return x;
        } else {
            Node<E> x = last;
            for (int i = size - 1; i > index; i--)
                x = x.prev;
            return x;
        }
    }
}
